package com.example.netdemo.retrofit

import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData

object ResourceHandler {
    fun <T> handle(
        resourceLiveData: LiveData<Resource<T>>,
        owner: LifecycleOwner,
        onLoading: (() -> Unit)? = null,
        onSuccess: (T) -> Unit,
        onError: ((String, Throwable?) -> Unit)? = { message, _ ->
            Toast.makeText(owner as? android.content.Context, message, Toast.LENGTH_SHORT).show()
        }
    ) {
        resourceLiveData.observe(owner) {
            when (it) {
                is Resource.Loading -> onLoading?.invoke()
                is Resource.Success -> onSuccess(it.data)
                is Resource.Error -> onError?.invoke(it.message, it.exception)
                else -> {}
            }
        }
    }

}